

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=light>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/set/B.svg">
  <link rel="icon" href="/img/set/B.svg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="程守斌">
  <meta name="keywords" content="">
  
    <meta name="description" content="常用开发原则1. 单一职责原则（Single Responsibility Principle，SRP）单一职责原则（Single Responsibility Principle，SRP）是面向对象设计中的一项基本原则，它指出一个类或模块应该只有一个职责或责任，即一个类或模块应该只负责一种功能或行为。 单一职责原则的目的是将复杂的系统分解为多个简单的组件，每个组件都只关注一个特定的功能或职责，从">
<meta property="og:type" content="article">
<meta property="og:title" content="常用开发原则">
<meta property="og:url" content="https://icoobin.github.io/2023/02/25/other/%E5%B8%B8%E7%94%A8%E5%BC%80%E5%8F%91%E5%8E%9F%E5%88%99/index.html">
<meta property="og:site_name" content="Bin&#39;s blog">
<meta property="og:description" content="常用开发原则1. 单一职责原则（Single Responsibility Principle，SRP）单一职责原则（Single Responsibility Principle，SRP）是面向对象设计中的一项基本原则，它指出一个类或模块应该只有一个职责或责任，即一个类或模块应该只负责一种功能或行为。 单一职责原则的目的是将复杂的系统分解为多个简单的组件，每个组件都只关注一个特定的功能或职责，从">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-25T03:35:09.000Z">
<meta property="article:modified_time" content="2023-02-27T05:37:29.398Z">
<meta property="article:author" content="程守斌">
<meta property="article:tag" content="设计模式">
<meta property="article:tag" content="Swift">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>常用开发原则 - Bin&#39;s blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"icoobin.github.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"|","loop":false,"scope":["home","post"]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/set/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"0424c6a81239810100c98bd470a50118","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?0424c6a81239810100c98bd470a50118";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 38.2vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Bin&#39;s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/banner/posts.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="常用开发原则"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-25 11:35" pubdate>
          2023年2月25日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          13k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          106 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">常用开发原则</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="常用开发原则"><a href="#常用开发原则" class="headerlink" title="常用开发原则"></a>常用开发原则</h2><h3 id="1-单一职责原则（Single-Responsibility-Principle，SRP）"><a href="#1-单一职责原则（Single-Responsibility-Principle，SRP）" class="headerlink" title="1. 单一职责原则（Single Responsibility Principle，SRP）"></a>1. 单一职责原则（Single Responsibility Principle，SRP）</h3><p>单一职责原则（Single Responsibility Principle，SRP）是面向对象设计中的一项基本原则，它指出一个类或模块应该只有一个职责或责任，即一个类或模块应该只负责一种功能或行为。</p>
<p>单一职责原则的目的是将复杂的系统分解为多个简单的组件，每个组件都只关注一个特定的功能或职责，从而使系统更加灵活、可扩展和易于维护。当一个类或模块承担了多种职责时，它就变得复杂、难以维护和扩展，因为修改其中一个职责可能会影响到其他职责。</p>
<p>单一职责原则常用来解决以下问题：</p>
<ul>
<li>类或模块过于庞大，难以维护和理解；</li>
<li>类或模块承担了过多的职责，难以扩展和重用；</li>
<li>修改一个职责会影响到其他职责，导致系统出现不稳定的行为。</li>
</ul>
<p>下面是一个使用 Swift 5 实现单一职责原则的示例。我们有一个 <strong><code>Order</code></strong> 类，用于表示客户订单，其中包含了订单的详细信息以及订单的处理方法。我们可以将 <strong><code>Order</code></strong> 类拆分成两个类，一个用于表示订单信息，另一个用于处理订单，从而使其符合单一职责原则。</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 订单信息类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">OrderInfo</span> &#123;
    <span class="hljs-keyword">let</span> orderId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> customerName: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> orderDate: <span class="hljs-type">Date</span>
    <span class="hljs-keyword">let</span> orderItems: [<span class="hljs-type">OrderItem</span>]

    <span class="hljs-keyword">init</span>(<span class="hljs-params">orderId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">customerName</span>: <span class="hljs-type">String</span>, <span class="hljs-params">orderDate</span>: <span class="hljs-type">Date</span>, <span class="hljs-params">orderItems</span>: [<span class="hljs-type">OrderItem</span>]) &#123;
        <span class="hljs-keyword">self</span>.orderId <span class="hljs-operator">=</span> orderId
        <span class="hljs-keyword">self</span>.customerName <span class="hljs-operator">=</span> customerName
        <span class="hljs-keyword">self</span>.orderDate <span class="hljs-operator">=</span> orderDate
        <span class="hljs-keyword">self</span>.orderItems <span class="hljs-operator">=</span> orderItems
    &#125;
&#125;

<span class="hljs-comment">// 订单处理类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">OrderProcessor</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">process</span>(<span class="hljs-params">order</span>: <span class="hljs-type">OrderInfo</span>) &#123;
        <span class="hljs-comment">// 处理订单逻辑</span>
    &#125;
&#125;</code></pre></div>
<p>在上面的示例中，我们将 <strong><code>Order</code></strong> 类拆分成了 <strong><code>OrderInfo</code></strong> 和 <strong><code>OrderProcessor</code></strong> 两个类。**<code>OrderInfo</code>** 类用于表示订单的详细信息，包括订单编号、客户名称、下单日期和订单项；**<code>OrderProcessor</code>** 类用于处理订单，包括处理订单的逻辑和实现。</p>
<p>通过将 <strong><code>Order</code></strong> 类拆分成多个类，我们遵守了单一职责原则，使每个类只关注一种特定的功能或职责。这样，如果我们需要修改订单处理逻辑，就不会影响到订单信息的表示和存储，从而使系统更加稳定和易于维护。</p>
<h3 id="2-开放封闭原则（Open-x2F-Closed-Principle，OCP）"><a href="#2-开放封闭原则（Open-x2F-Closed-Principle，OCP）" class="headerlink" title="2. 开放封闭原则（Open&#x2F;Closed Principle，OCP）"></a>2. 开放封闭原则（Open&#x2F;Closed Principle，OCP）</h3><p>开放封闭原则（Open&#x2F;Closed Principle，OCP）是面向对象设计中的一项基本原则，它指出一个软件实体（类、模块、函数等）应该对扩展开放，对修改封闭。这意味着在不修改原有代码的情况下，可以通过扩展代码的行为来实现新的功能。</p>
<p>开放封闭原则的目的是保持系统的稳定性和可维护性。当系统需要修改现有代码来添加新的功能时，可能会导致系统出现不稳定的行为和意外的副作用。通过遵守开放封闭原则，我们可以避免这些问题，同时使系统更加灵活和易于扩展。</p>
<p>开放封闭原则常用来解决以下问题：</p>
<ul>
<li>当需要添加新的功能时，不希望修改现有的代码；</li>
<li>当需要修改现有的代码时，不希望影响到系统的稳定性和可维护性。</li>
</ul>
<p>下面是一个使用 Swift 5 实现开放封闭原则的示例。我们有一个 <strong><code>OrderProcessor</code></strong> 类，用于处理客户订单，其中包含了订单的详细信息以及订单的处理方法。我们希望能够通过添加新的支付方式来扩展订单处理逻辑，同时不影响现有的代码。为了实现这个目标，我们可以将支付逻辑封装到一个单独的类中，从而使其可以独立扩展和修改。</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 订单信息类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">OrderInfo</span> &#123;
    <span class="hljs-keyword">let</span> orderId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> customerName: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> orderDate: <span class="hljs-type">Date</span>
    <span class="hljs-keyword">let</span> orderItems: [<span class="hljs-type">OrderItem</span>]

    <span class="hljs-keyword">init</span>(<span class="hljs-params">orderId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">customerName</span>: <span class="hljs-type">String</span>, <span class="hljs-params">orderDate</span>: <span class="hljs-type">Date</span>, <span class="hljs-params">orderItems</span>: [<span class="hljs-type">OrderItem</span>]) &#123;
        <span class="hljs-keyword">self</span>.orderId <span class="hljs-operator">=</span> orderId
        <span class="hljs-keyword">self</span>.customerName <span class="hljs-operator">=</span> customerName
        <span class="hljs-keyword">self</span>.orderDate <span class="hljs-operator">=</span> orderDate
        <span class="hljs-keyword">self</span>.orderItems <span class="hljs-operator">=</span> orderItems
    &#125;
&#125;

<span class="hljs-comment">// 支付接口</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Payment</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">pay</span>(<span class="hljs-params">amount</span>: <span class="hljs-type">Double</span>)
&#125;

<span class="hljs-comment">// 现金支付类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">CashPayment</span>: <span class="hljs-title class_">Payment</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">pay</span>(<span class="hljs-params">amount</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-comment">// 现金支付逻辑</span>
    &#125;
&#125;

<span class="hljs-comment">// 支付宝支付类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">AlipayPayment</span>: <span class="hljs-title class_">Payment</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">pay</span>(<span class="hljs-params">amount</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-comment">// 支付宝支付逻辑</span>
    &#125;
&#125;

<span class="hljs-comment">// 订单处理类</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">OrderProcessor</span> &#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> payment: <span class="hljs-type">Payment</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">payment</span>: <span class="hljs-type">Payment</span>) &#123;
        <span class="hljs-keyword">self</span>.payment <span class="hljs-operator">=</span> payment
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">process</span>(<span class="hljs-params">order</span>: <span class="hljs-type">OrderInfo</span>) &#123;
        <span class="hljs-comment">// 处理订单逻辑</span>

        <span class="hljs-comment">// 支付订单</span>
        payment.pay(amount: order.totalAmount)
    &#125;
&#125;</code></pre></div>
<p>在上面的示例中，我们将支付逻辑封装到了 <strong><code>Payment</code></strong> 接口中，并实现了两个具体的支付类 <strong><code>CashPayment</code></strong> 和 **<code>AlipayPayment</code>**。我们还将支付逻辑注入到了 <strong><code>OrderProcessor</code></strong> 类中，通过传递不同的支付类实现订单处理的扩展和修改。</p>
<p>通过将支付逻辑封装到一个单独的类中，我们可以在不影响现有代码的情况下，添加新的支付方式和修改支付逻辑，从而实现了开放封闭原则。当需要添加新的支付方式时，我们只需要实现一个新的支付类并注入到 <strong><code>OrderProcessor</code></strong> 中即可，不需要修改现有的代码。</p>
<p>下面是一个示例代码，用于创建一个现金支付订单：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">let</span> order <span class="hljs-operator">=</span> <span class="hljs-type">OrderInfo</span>(orderId: <span class="hljs-string">&quot;123456&quot;</span>, customerName: <span class="hljs-string">&quot;张三&quot;</span>, orderDate: <span class="hljs-type">Date</span>(), orderItems: [item1, item2])
<span class="hljs-keyword">let</span> cashPayment <span class="hljs-operator">=</span> <span class="hljs-type">CashPayment</span>()
<span class="hljs-keyword">let</span> orderProcessor <span class="hljs-operator">=</span> <span class="hljs-type">OrderProcessor</span>(payment: cashPayment)
orderProcessor.process(order: order)</code></pre></div>
<p>我们还可以创建一个支付宝支付订单：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">let</span> order <span class="hljs-operator">=</span> <span class="hljs-type">OrderInfo</span>(orderId: <span class="hljs-string">&quot;123456&quot;</span>, customerName: <span class="hljs-string">&quot;张三&quot;</span>, orderDate: <span class="hljs-type">Date</span>(), orderItems: [item1, item2])
<span class="hljs-keyword">let</span> alipayPayment <span class="hljs-operator">=</span> <span class="hljs-type">AlipayPayment</span>()
<span class="hljs-keyword">let</span> orderProcessor <span class="hljs-operator">=</span> <span class="hljs-type">OrderProcessor</span>(payment: alipayPayment)
orderProcessor.process(order: order)</code></pre></div>
<p>通过实现开放封闭原则，我们使系统更加灵活和易于扩展，同时保持了系统的稳定性和可维护性。</p>
<h3 id="3-里式替换原则（Liskov-Substitution-Principle，LSP）"><a href="#3-里式替换原则（Liskov-Substitution-Principle，LSP）" class="headerlink" title="3. 里式替换原则（Liskov Substitution Principle，LSP）"></a>3. 里式替换原则（Liskov Substitution Principle，LSP）</h3><p>里式替换原则（Liskov Substitution Principle，LSP）是面向对象设计中的一个重要原则，它指出：子类对象应该能够替换掉父类对象并且仍能保持程序的正确性。</p>
<p>这个原则的核心思想是：子类不应该破坏父类的封装和抽象，即子类中新增的方法和属性不应该影响到父类的行为。LSP可以帮助我们确保代码的正确性和可扩展性，同时也可以避免出现一些难以调试的问题。</p>
<p>下面，我们以一个简单的 Swift 示例来说明 LSP 的应用。假设我们有一个图形库，其中包含 <strong><code>Shape</code></strong> 基类和两个子类 <strong><code>Rectangle</code></strong> 和 <strong><code>Circle</code><strong>。</strong><code>Shape</code></strong> 类有一个计算面积的方法 <strong><code>calculateArea()</code><strong>，</strong><code>Rectangle</code></strong> 和 <strong><code>Circle</code></strong> 分别实现了这个方法。我们可以使用这些类来创建不同的图形，并计算它们的面积。</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateArea</span>() -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-built_in">fatalError</span>(<span class="hljs-string">&quot;This method must be overridden&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Rectangle</span>: <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">var</span> width: <span class="hljs-type">Double</span>
    <span class="hljs-keyword">var</span> height: <span class="hljs-type">Double</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">width</span>: <span class="hljs-type">Double</span>, <span class="hljs-params">height</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.width <span class="hljs-operator">=</span> width
        <span class="hljs-keyword">self</span>.height <span class="hljs-operator">=</span> height
    &#125;

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateArea</span>() -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> width <span class="hljs-operator">*</span> height
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Circle</span>: <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">var</span> radius: <span class="hljs-type">Double</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">radius</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.radius <span class="hljs-operator">=</span> radius
    &#125;

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateArea</span>() -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-type">Double</span>.pi <span class="hljs-operator">*</span> radius <span class="hljs-operator">*</span> radius
    &#125;
&#125;</code></pre></div>
<p>现在，我们希望在图形库中添加一个新的图形类 **<code>Square</code>**，它是 <strong><code>Rectangle</code></strong> 的一个特例，即它的宽和高相等。按照 LSP 的原则，我们应该可以将 <strong><code>Square</code></strong> 对象替换为 <strong><code>Rectangle</code></strong> 对象而不会影响程序的正确性。</p>
<p>我们可以创建一个 <strong><code>Square</code></strong> 类继承自 **<code>Rectangle</code>**，并重写父类的初始化方法，确保 <strong><code>width</code></strong> 和 <strong><code>height</code></strong> 始终相等：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span>: <span class="hljs-title class_">Rectangle</span> &#123;
    <span class="hljs-keyword">init</span>(<span class="hljs-params">side</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>(width: side, height: side)
    &#125;
&#125;</code></pre></div>
<p>现在，我们可以在创建图形时使用 <strong><code>Square</code></strong> 替换 <strong><code>Rectangle</code></strong> 对象，并调用 <strong><code>calculateArea()</code></strong> 方法计算面积：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">let</span> rectangle <span class="hljs-operator">=</span> <span class="hljs-type">Rectangle</span>(width: <span class="hljs-number">4</span>, height: <span class="hljs-number">5</span>)
<span class="hljs-keyword">let</span> circle <span class="hljs-operator">=</span> <span class="hljs-type">Circle</span>(radius: <span class="hljs-number">3</span>)
<span class="hljs-keyword">let</span> square <span class="hljs-operator">=</span> <span class="hljs-type">Square</span>(side: <span class="hljs-number">4</span>)

<span class="hljs-keyword">let</span> shapes: [<span class="hljs-type">Shape</span>] <span class="hljs-operator">=</span> [rectangle, circle, square]

<span class="hljs-keyword">for</span> shape <span class="hljs-keyword">in</span> shapes &#123;
    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Area of <span class="hljs-subst">\(<span class="hljs-built_in">type</span>(of: shape))</span> is <span class="hljs-subst">\(shape.calculateArea())</span>&quot;</span>)
&#125;</code></pre></div>
<div class="code-wrapper"><pre><code class="hljs">输出结果如下：
</code></pre></div>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-type">Area</span> of <span class="hljs-type">Rectangle</span> <span class="hljs-keyword">is</span> <span class="hljs-number">20.0</span>
<span class="hljs-type">Area</span> of <span class="hljs-type">Circle</span> <span class="hljs-keyword">is</span> <span class="hljs-number">28.274333882308138</span>
<span class="hljs-type">Area</span> of <span class="hljs-type">Square</span> <span class="hljs-keyword">is</span> <span class="hljs-number">16.0</span></code></pre></div>
<p>由于 <strong><code>Square</code></strong> 对象是 <strong><code>Rectangle</code></strong> 的特例，我们可以使用 <strong><code>Square</code></strong> 对象替换 <strong><code>Rectangle</code></strong> 对象而不影响程序的正确性。这就是 LSP 的应用途，通过使用 LSP，我们可以创建更加灵活的代码，可以轻松地添加新的子类，并在不破坏现有代码的情况下进行修改和扩展。</p>
<p>在实际开发中，为了遵循 LSP 原则，我们需要遵循以下几个准则：</p>
<ul>
<li>子类必须实现父类的所有方法，并且方法的输入输出参数类型与父类一致或者更加宽松。</li>
<li>子类新增的方法和属性不应该影响到父类的行为。</li>
<li>子类的前置条件（输入参数）不能强于父类的前置条件。</li>
<li>子类的后置条件（输出参数）不能弱于父类的后置条件。</li>
</ul>
<p>下面，我们再以一个 Swift 示例来说明 LSP 的应用。假设我们有一个计算器应用，其中包含一个 <strong><code>Calculator</code></strong> 基类和两个子类 <strong><code>SimpleCalculator</code></strong> 和 <strong><code>ScientificCalculator</code><strong>。</strong><code>Calculator</code></strong> 类有一个计算方法 <strong><code>calculate(_:)</code><strong>，</strong><code>SimpleCalculator</code></strong> 和 <strong><code>ScientificCalculator</code></strong> 分别实现了这个方法。我们可以使用这些类来进行简单的数学计算。</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Calculator</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculate</span>(<span class="hljs-keyword">_</span> <span class="hljs-params">expression</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-built_in">fatalError</span>(<span class="hljs-string">&quot;This method must be overridden&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">SimpleCalculator</span>: <span class="hljs-title class_">Calculator</span> &#123;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculate</span>(<span class="hljs-keyword">_</span> <span class="hljs-params">expression</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-comment">// 简单计算逻辑</span>
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">ScientificCalculator</span>: <span class="hljs-title class_">Calculator</span> &#123;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculate</span>(<span class="hljs-keyword">_</span> <span class="hljs-params">expression</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-comment">// 科学计算逻辑</span>
    &#125;
&#125;</code></pre></div>
<p>现在，我们希望添加一个新的子类 **<code>GraphingCalculator</code>**，它可以将计算结果以图表的形式展示出来。按照 LSP 的原则，我们应该可以将 <strong><code>GraphingCalculator</code></strong> 对象替换为 <strong><code>SimpleCalculator</code></strong> 或 <strong><code>ScientificCalculator</code></strong> 对象而不会影响程序的正确性。</p>
<p>我们可以创建一个 <strong><code>GraphingCalculator</code></strong> 类，它继承自 **<code>Calculator</code>**，并实现 <strong><code>calculate(_:)</code></strong> 方法：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">class</span> <span class="hljs-title class_">GraphingCalculator</span>: <span class="hljs-title class_">Calculator</span> &#123;
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculate</span>(<span class="hljs-keyword">_</span> <span class="hljs-params">expression</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">let</span> result <span class="hljs-operator">=</span> <span class="hljs-keyword">super</span>.calculate(expression)
        <span class="hljs-comment">// 将计算结果以图表的形式展示出来</span>
        <span class="hljs-keyword">return</span> result
    &#125;
&#125;</code></pre></div>
<p>现在，我们可以使用 <strong><code>GraphingCalculator</code></strong> 对象来进行数学计算，并将计算结果以图表的形式展示出来：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">let</span> simpleCalculator <span class="hljs-operator">=</span> <span class="hljs-type">SimpleCalculator</span>()
<span class="hljs-keyword">let</span> scientificCalculator <span class="hljs-operator">=</span> <span class="hljs-type">ScientificCalculator</span>()
<span class="hljs-keyword">let</span> graphingCalculator <span class="hljs-operator">=</span> <span class="hljs-type">GraphingCalculator</span>()

<span class="hljs-keyword">let</span> expressions <span class="hljs-operator">=</span> [<span class="hljs-string">&quot;2 + 2&quot;</span>, <span class="hljs-string">&quot;sin(45)&quot;</span>, <span class="hljs-string">&quot;log(10)&quot;</span>]

<span class="hljs-keyword">for</span> expression <span class="hljs-keyword">in</span> expressions &#123;
    <span class="hljs-keyword">let</span> simpleResult <span class="hljs-operator">=</span> simpleCalculator.calculate(expression)
    <span class="hljs-keyword">let</span> scientificResult <span class="hljs-operator">=</span> scientificCalculator.calculate(expression)
    <span class="hljs-keyword">let</span> graphingResult <span class="hljs-operator">=</span> graphingCalculator.calculate(expression)

    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Simple: <span class="hljs-subst">\(simpleResult)</span>, Scientific: <span class="hljs-subst">\(scientificResult)</span>, Graphing: <span class="hljs-subst">\(graphingResult)</span>&quot;</span>)
&#125;</code></pre></div>
<p>输出结果如下：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-type">Simple</span>: <span class="hljs-number">4.0</span>, <span class="hljs-type">Scientific</span>: <span class="hljs-number">0.8509035245341184</span>, <span class="hljs-type">Graphing</span>: <span class="hljs-number">4.0</span>
<span class="hljs-type">Simple</span>: <span class="hljs-number">0.8509035245341184</span>,<span class="hljs-type">Scientific</span>: <span class="hljs-number">0.8509035245341184</span>, <span class="hljs-type">Graphing</span>: <span class="hljs-number">0.8509035245341184</span>
<span class="hljs-type">Simple</span>: <span class="hljs-number">2.302585092994046</span>, <span class="hljs-type">Scientific</span>: <span class="hljs-number">2.302585092994046</span>, <span class="hljs-type">Graphing</span>: <span class="hljs-number">2.302585092994046</span></code></pre></div>
<p>可以看到，我们成功地将 <code>GraphingCalculator</code> 对象替换为 <code>SimpleCalculator</code> 和 <code>ScientificCalculator</code> 对象，而不会影响程序的正确性。这就是 LSP 的优势。</p>
<p>总之，LSP 是一个非常重要的面向对象编程原则，它可以帮助我们创建灵活、可扩展、易于维护的代码。为了遵循 LSP，我们需要在设计类的时候遵循一些基本的规则，并保证子类可以完全替换父类，而不会影响程序的正确性。</p>
<h3 id="4-接口隔离原则（Interface-Segregation-Principle，ISP）"><a href="#4-接口隔离原则（Interface-Segregation-Principle，ISP）" class="headerlink" title="4. 接口隔离原则（Interface Segregation Principle，ISP）"></a>4. 接口隔离原则（Interface Segregation Principle，ISP）</h3><p>接口隔离原则（Interface Segregation Principle，ISP）是面向对象编程中的一条原则，它指出“客户端不应该被迫依赖于它不使用的方法”。换句话说，如果一个接口的方法过于冗杂，一个类可能不得不实现一些它并不需要的方法。这不仅浪费了时间和资源，而且会导致代码的复杂性和脆弱性。</p>
<p>ISP 的主要目的是分离接口，将大型、复杂的接口分解为更小、更简单的接口，以便客户端只需知道与其相关的方法。这样，客户端就不必担心不需要的方法，而只需要专注于与其相关的方法。</p>
<p>为了遵循 ISP，我们需要在设计接口时考虑到客户端的需要，并将其分解为更小、更简单的接口。这样，客户端只需要依赖它们需要的接口，而不必依赖于整个接口。</p>
<p>下面是一个使用 ISP 的例子。假设我们正在设计一个图形编辑器，其中有多种形状（如矩形、圆形、三角形等）。每个形状都可以绘制、移动、调整大小等。我们可以将这些操作定义在一个大型的 <strong><code>Shape</code></strong> 接口中，如下所示：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Shape</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>()
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">move</span>(<span class="hljs-params">to</span> <span class="hljs-params">point</span>: <span class="hljs-type">CGPoint</span>)
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">resize</span>(<span class="hljs-params">to</span> <span class="hljs-params">size</span>: <span class="hljs-type">CGSize</span>)
&#125;</code></pre></div>
<p>然而，如果我们这样设计，那么所有的形状都必须实现所有的方法，即使它们并不需要某些方法。这显然不符合 ISP。为了解决这个问题，我们可以将这个大型接口拆分为多个更小、更专业的接口，如下所示：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Drawable</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">draw</span>()
&#125;

<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Movable</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">move</span>(<span class="hljs-params">to</span> <span class="hljs-params">point</span>: <span class="hljs-type">CGPoint</span>)
&#125;

<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Resizable</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">resize</span>(<span class="hljs-params">to</span> <span class="hljs-params">size</span>: <span class="hljs-type">CGSize</span>)
&#125;

<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Shape</span>: <span class="hljs-title class_">Drawable</span>, <span class="hljs-title class_">Movable</span>, <span class="hljs-title class_">Resizable</span> &#123;&#125;</code></pre></div>
<p>现在，我们的每个形状只需要实现与其相关的方法。例如，圆形只需要实现 <strong><code>Drawable</code></strong> 和 <strong><code>Resizable</code></strong> 接口，而不需要实现 <strong><code>Movable</code></strong> 接口。这样，我们的代码就更加灵活，易于扩展和维护了。</p>
<p>总之，ISP 是一个非常重要的面向对象编程原则，它可以帮助我们创建灵活、可扩展、易于维护的代码。为了遵循 ISP，我们需要在设计接口时考虑客户端的需要，并将其拆分为更小、更简单的接口。</p>
<h3 id="5-迪米特法则（Law-of-Demeter，LoD）"><a href="#5-迪米特法则（Law-of-Demeter，LoD）" class="headerlink" title="5. 迪米特法则（Law of Demeter，LoD）"></a>5. 迪米特法则（Law of Demeter，LoD）</h3><p>迪米特法则（Law of Demeter，LoD）也称为最少知识原则（Principle of Least Knowledge），是面向对象编程中的一条设计原则，它强调一个对象应该尽可能少地了解其他对象，并且只和它们的直接朋友（成员变量、方法参数等）通信，而不与非直接朋友进行通信。</p>
<p>迪米特法则的目的是减少类之间的耦合度，提高系统的稳定性、可维护性和可扩展性。当一个类依赖的其他类太多时，如果这些依赖的类发生了改变，就会对该类产生较大的影响，从而导致代码的复杂度增加。因此，遵循迪米特法则可以使得类之间的耦合度降低，从而使得代码更加模块化、易于维护和重构。</p>
<p>下面以 Swift 5 代码举例，展示如何使用迪米特法则来减少类之间的耦合度。假设我们有一个订单类，它需要依赖客户类和商品类来进行处理：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Order</span> &#123;
    <span class="hljs-keyword">var</span> customerId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> productId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> quantity: <span class="hljs-type">Int</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">customerId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">productId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">quantity</span>: <span class="hljs-type">Int</span>) &#123;
        <span class="hljs-keyword">self</span>.customerId <span class="hljs-operator">=</span> customerId
        <span class="hljs-keyword">self</span>.productId <span class="hljs-operator">=</span> productId
        <span class="hljs-keyword">self</span>.quantity <span class="hljs-operator">=</span> quantity
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateTotal</span>() -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">let</span> customer <span class="hljs-operator">=</span> <span class="hljs-type">Customer</span>.getCustomerById(customerId: customerId)
        <span class="hljs-keyword">let</span> product <span class="hljs-operator">=</span> <span class="hljs-type">Product</span>.getProductById(productId: productId)
        <span class="hljs-keyword">let</span> totalPrice <span class="hljs-operator">=</span> <span class="hljs-type">Double</span>(quantity) <span class="hljs-operator">*</span> product.price
        <span class="hljs-keyword">return</span> totalPrice
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Customer</span> &#123;
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">getCustomerById</span>(<span class="hljs-params">customerId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Customer</span> &#123;
        <span class="hljs-comment">// 模拟获取客户对象的过程</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Customer</span>(id: customerId, name: <span class="hljs-string">&quot;&quot;</span>)
    &#125;

    <span class="hljs-keyword">var</span> id: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">id</span>: <span class="hljs-type">String</span>, <span class="hljs-params">name</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">self</span>.id <span class="hljs-operator">=</span> id
        <span class="hljs-keyword">self</span>.name <span class="hljs-operator">=</span> name
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Product</span> &#123;
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">getProductById</span>(<span class="hljs-params">productId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Product</span> &#123;
        <span class="hljs-comment">// 模拟获取商品对象的过程</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Product</span>(id: productId, name: <span class="hljs-string">&quot;&quot;</span>, price: <span class="hljs-number">0.0</span>)
    &#125;

    <span class="hljs-keyword">var</span> id: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> price: <span class="hljs-type">Double</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">id</span>: <span class="hljs-type">String</span>, <span class="hljs-params">name</span>: <span class="hljs-type">String</span>, <span class="hljs-params">price</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.id <span class="hljs-operator">=</span> id
        <span class="hljs-keyword">self</span>.name <span class="hljs-operator">=</span> name
        <span class="hljs-keyword">self</span>.price <span class="hljs-operator">=</span> price
    &#125;
&#125;</code></pre></div>
<p>在上述代码中，订单类依赖了客户类和商品类的静态方法，通过这些静态方法获取了客户对象和商品对象。这种方式违反了迪米特法则，因为订单类不仅需要了解客户类和商品类的接口，还需要了解它们的具体实现细节。</p>
<p>为了遵循迪米特法则，我们可以通过依赖注入的方式，来减少订单类对客户类和商品类的依赖。下面是修改后的代码：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-keyword">protocol</span> <span class="hljs-title class_">CustomerProtocol</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">getCustomerById</span>(<span class="hljs-params">customerId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Customer</span>
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">CustomerService</span>: <span class="hljs-title class_">CustomerProtocol</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">getCustomerById</span>(<span class="hljs-params">customerId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Customer</span> &#123;
        <span class="hljs-comment">// 模拟获取客户对象的过程</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Customer</span>(id: customerId, name: <span class="hljs-string">&quot;&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">ProductProtocol</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">getProductById</span>(<span class="hljs-params">productId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Product</span>
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">ProductService</span>: <span class="hljs-title class_">ProductProtocol</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">getProductById</span>(<span class="hljs-params">productId</span>: <span class="hljs-type">String</span>) -&gt; <span class="hljs-type">Product</span> &#123;
        <span class="hljs-comment">// 模拟获取商品对象的过程</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Product</span>(id: productId, name: <span class="hljs-string">&quot;&quot;</span>, price: <span class="hljs-number">0.0</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Order</span> &#123;
    <span class="hljs-keyword">var</span> customerId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> productId: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> quantity: <span class="hljs-type">Int</span>
    <span class="hljs-keyword">var</span> customerService: <span class="hljs-type">CustomerProtocol</span>
    <span class="hljs-keyword">var</span> productService: <span class="hljs-type">ProductProtocol</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">customerId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">productId</span>: <span class="hljs-type">String</span>, <span class="hljs-params">quantity</span>: <span class="hljs-type">Int</span>, <span class="hljs-params">customerService</span>: <span class="hljs-type">CustomerProtocol</span>, <span class="hljs-params">productService</span>: <span class="hljs-type">ProductProtocol</span>) &#123;
        <span class="hljs-keyword">self</span>.customerId <span class="hljs-operator">=</span> customerId
        <span class="hljs-keyword">self</span>.productId <span class="hljs-operator">=</span> productId
        <span class="hljs-keyword">self</span>.quantity <span class="hljs-operator">=</span> quantity
        <span class="hljs-keyword">self</span>.customerService <span class="hljs-operator">=</span> customerService
        <span class="hljs-keyword">self</span>.productService <span class="hljs-operator">=</span> productService
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">calculateTotal</span>() -&gt; <span class="hljs-type">Double</span> &#123;
        <span class="hljs-keyword">let</span> customer <span class="hljs-operator">=</span> customerService.getCustomerById(customerId: customerId)
        <span class="hljs-keyword">let</span> product <span class="hljs-operator">=</span> productService.getProductById(productId: productId)
        <span class="hljs-keyword">let</span> totalPrice <span class="hljs-operator">=</span> <span class="hljs-type">Double</span>(quantity) <span class="hljs-operator">*</span> product.price
        <span class="hljs-keyword">return</span> totalPrice
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Customer</span> &#123;
    <span class="hljs-keyword">var</span> id: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">id</span>: <span class="hljs-type">String</span>, <span class="hljs-params">name</span>: <span class="hljs-type">String</span>) &#123;
        <span class="hljs-keyword">self</span>.id <span class="hljs-operator">=</span> id
        <span class="hljs-keyword">self</span>.name <span class="hljs-operator">=</span> name
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Product</span> &#123;
    <span class="hljs-keyword">var</span> id: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span>
    <span class="hljs-keyword">var</span> price: <span class="hljs-type">Double</span>

    <span class="hljs-keyword">init</span>(<span class="hljs-params">id</span>: <span class="hljs-type">String</span>, <span class="hljs-params">name</span>: <span class="hljs-type">String</span>, <span class="hljs-params">price</span>: <span class="hljs-type">Double</span>) &#123;
        <span class="hljs-keyword">self</span>.id <span class="hljs-operator">=</span> id
        <span class="hljs-keyword">self</span>.name <span class="hljs-operator">=</span> name
        <span class="hljs-keyword">self</span>.price <span class="hljs-operator">=</span> price
    &#125;
&#125;</code></pre></div>
<p>在上述代码中，我们使用协议和依赖注入的方式来降低订单类对客户类和商品类的耦合度。具体来说，我们定义了两个协议 <code>CustomerProtocol</code> 和 <code>ProductProtocol</code>，分别包含了获取客户对象和商品对象的方法。然后我们实现了两个具体的服务类 <code>CustomerService</code> 和 <code>ProductService</code>，它们分别实现了上述协议中定义的方法，用于提供客户对象和商品对象的获取功能。</p>
<p>接下来，我们修改了订单类的构造函数，将客户服务对象和商品服务对象作为参数传入。在 calculateTotal 方法中，我们不再直接调用客户类和商品类的静态方法，而是通过客户服务对象和商品服务对象来获取客户对象和商品对象。这样一来，订单类只依赖了客户服务类和商品服务类的接口，而不再依赖它们的具体实现细节，这就遵循了迪米特法则。</p>
<p>总之，迪米特法则是一条重要的设计原则，它可以帮助我们减少类之间的耦合度，提高系统的稳定性、可维护性和可扩展性。在编写代码时，我们应该尽可能地遵循这个原则，尽量减少类之间的交互，使得每个类的职责更加清晰，代码结构更加简单易懂，从而使得代码更加健壮和可维护。</p>
<p>需要注意的是，在实际开发中，迪米特法则并不是一个银弹，它并不能解决所有的问题，也不能被简单地应用到所有的场景中。在某些情况下，迪米特法则可能会导致类之间的通信变得复杂，从而降低系统的效率和性能。因此，在应用迪米特法则时，我们需要根据具体的情况来灵活运用，综合考虑各种因素，找到最合适的设计方案。</p>
<p>“银弹”是一个编程界中的术语，指的是一种能够解决所有问题的神奇解决方案。因此，“迪米特法则并不是一个银弹”意味着迪米特法则并不能解决所有问题，我们需要根据具体情况进行灵活应用和综合考虑。</p>
<h3 id="6-依赖倒置原则（Dependency-Inversion-Principle，DIP）"><a href="#6-依赖倒置原则（Dependency-Inversion-Principle，DIP）" class="headerlink" title="6. 依赖倒置原则（Dependency Inversion Principle，DIP）"></a>6. 依赖倒置原则（Dependency Inversion Principle，DIP）</h3><p>依赖倒置原则（Dependency Inversion Principle，DIP）是面向对象设计中的一个重要原则，它强调高层模块不应该依赖低层模块，它们都应该依赖于抽象；而抽象不应该依赖于细节，细节应该依赖于抽象。简单来说，就是要面向接口编程，而不是面向实现编程。</p>
<p>依赖倒置原则的作用是降低模块之间的耦合度，提高代码的灵活性、可扩展性和可维护性。它可以避免在修改一个模块时，对其他模块造成影响，同时也能够方便地进行单元测试和模块重用。</p>
<p>下面是使用 Swift 5 实现依赖倒置原则的一个示例：</p>
<div class="code-wrapper"><pre><code class="hljs swift"><span class="hljs-comment">// 定义一个协议</span>
<span class="hljs-keyword">protocol</span> <span class="hljs-title class_">Animal</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">makeSound</span>()
&#125;

<span class="hljs-comment">// 实现两个类，它们都遵循了 Animal 协议</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Cat</span>: <span class="hljs-title class_">Animal</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">makeSound</span>() &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Meow&quot;</span>)
    &#125;
&#125;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Dog</span>: <span class="hljs-title class_">Animal</span> &#123;
    <span class="hljs-keyword">func</span> <span class="hljs-title function_">makeSound</span>() &#123;
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Woof&quot;</span>)
    &#125;
&#125;

<span class="hljs-comment">// 定义一个高层模块，它依赖于 Animal 协议</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">AnimalShelter</span> &#123;
    <span class="hljs-keyword">var</span> animals: [<span class="hljs-type">Animal</span>] <span class="hljs-operator">=</span> []

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">addAnimal</span>(<span class="hljs-params">animal</span>: <span class="hljs-type">Animal</span>) &#123;
        animals.append(animal)
    &#125;

    <span class="hljs-keyword">func</span> <span class="hljs-title function_">makeAllAnimalsSound</span>() &#123;
        <span class="hljs-keyword">for</span> animal <span class="hljs-keyword">in</span> animals &#123;
            animal.makeSound()
        &#125;
    &#125;
&#125;

<span class="hljs-comment">// 在客户端代码中，可以通过向 AnimalShelter 添加不同的 Animal 来实现不同的行为</span>
<span class="hljs-keyword">let</span> animalShelter <span class="hljs-operator">=</span> <span class="hljs-type">AnimalShelter</span>()
animalShelter.addAnimal(animal: <span class="hljs-type">Cat</span>())
animalShelter.addAnimal(animal: <span class="hljs-type">Dog</span>())
animalShelter.makeAllAnimalsSound()</code></pre></div>
<p>在上面的示例中，Animal 是一个抽象的概念，Cat 和 Dog 是具体的实现类。AnimalShelter 是一个高层模块，它不依赖于具体的实现类，而是依赖于 Animal 协议。在客户端代码中，可以通过向 AnimalShelter 添加不同的 Animal 来实现不同的行为，而不需要修改 AnimalShelter 类的代码。</p>
<p>这就是依赖倒置原则的一个实现，它通过引入抽象的概念，降低了 AnimalShelter 和具体实现类之间的耦合度，提高了代码的可扩展性和可维护性。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
        <a href="/tags/Swift/">#Swift</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>常用开发原则</div>
      <div>https://icoobin.github.io/2023/02/25/other/常用开发原则/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>程守斌</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/02/25/other/24-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-3-Swift-5%E7%89%88/" title="24 种设计模式-3 (Swift 5版)">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">24 种设计模式-3 (Swift 5版)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/02/25/other/hello-world/" title="Hello Hexo">
                        <span class="hidden-mobile">Hello Hexo</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
      <div class="col-lg-7 mx-auto nopadding-x-md">
        <div class="container custom mx-auto">
           <script src="/js/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script> <script>L2Dwidget.init({ pluginRootPath: "live2dw/", pluginJsPath: "lib/", pluginModelPath: "assets/", tagMode: !1, log: !1, model: { jsonPath: "/js/live2dw/assets/hijiki.model.json" }, display: { position: "left", hOffset: 60, vOffset: 0, width: 150, height: 300 }, mobile: { show: !1 } })</script> 
        </div>
      </div>
    
  </main>

  <footer>
    <div class="footer-inner">
    
        <div class="footer-content">
             <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
        </div>
        
            
                <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

                    
                        
                                    
</div>

<!-- <script src="js/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script>
<script>L2Dwidget.init({ pluginRootPath: "live2dw/", pluginJsPath: "lib/", pluginModelPath: "assets/", tagMode: !1, log: !1, model: { jsonPath: "js/live2dw/assets/hijiki.model.json" }, display: { position: "left", hOffset: 60, vOffset: 0, width: 150, height: 300 }, mobile: { show: !1 } })</script> -->

<!--
<div id="music_div" style="position: fixed; bottom: 0px; left: 30px;">
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=110
        src="//music.163.com/outchain/player?type=0&id=919444742&auto=1&height=90">
    </iframe>
    <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script src="/js/musicshow.js"></script>
</div>
-->

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
